package com.xingshang.controller;

import com.xingshang.model.po.Cart;
import com.xingshang.model.po.Category;
import com.xingshang.model.po.Goods;
import com.xingshang.model.po.User;
import com.xingshang.service.CartService;
import com.xingshang.service.CategoryService;
import com.xingshang.service.GoodsService;
import com.xingshang.service.impl.CartServiceImpl;
import jakarta.servlet.http.HttpSession;
import lombok.RequiredArgsConstructor;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Id;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Controller
@RequestMapping("/cart")
@RequiredArgsConstructor
public class CartController {
    private final CartService cartService;

    private final GoodsService goodsService;

    private final CategoryService categoryService;



    @GetMapping("/count")
    @ResponseBody
    public int count(HttpSession session) {
        User user = (User) session.getAttribute("user");
        List<Cart> cartList = cartService.getCartByUserId(user.getId());
        int num = cartList.size();
        System.out.println("购物车件数: " + num);
        session.setAttribute("cartNum", num);
        return num;
    }

    @PostMapping("/add")
    @ResponseBody
    public String add(@RequestParam Integer id, @RequestParam int num, HttpSession session){
        User user = (User) session.getAttribute("user");
//        System.out.println("id: " + id + "  num: " + num + "  user: " + user);
        if(user == null) {
            return "fail";
        }
        Goods goods = goodsService.getById(id);
        if(goods == null) {
            return "fail";
        }

        Cart cart1 = cartService.getCartByUserIdAndGoodsId(user.getId(), id);
//        System.out.println("cart1: " + cart1);
//        System.out.println("goods.getStock(): " + goods.getStock());
        if((cart1 == null || Objects.equals(cart1.getIsPay(), "Y") || Objects.equals(cart1.getIsDelete(), "Y")) && num > goods.getStock()) {
            return "f";
        }
        if((cart1 != null && Objects.equals(cart1.getIsPay(), "N") && Objects.equals(cart1.getIsDelete(), "N")) && num + cart1.getQuantity() > goods.getStock()) {
            return "f";
        }
        int cartNum = (int)session.getAttribute("cartNum");

        Cart cart = new Cart();
        cart.setGoodsId(id);
        cart.setUserId(user.getId());
        cart.setQuantity(num);
        int pd = cartService.addCart(cart);
//        System.out.println("pd: " + pd);
        if(pd > 0) {
            if(cart1 == null || Objects.equals(cart1.getIsPay(), "Y") || Objects.equals(cart1.getIsDelete(), "Y")) {
                session.setAttribute("cartNum", cartNum + 1);
            }
            System.out.println("cart1: "  + cart1);
            return "success";
        } else {
            return "fail";
        }
    }


    @PostMapping("/delete")
    @ResponseBody
    public String delete(@RequestParam Integer id, HttpSession session) {
        int pd = cartService.deleteCartById(id);
        if(pd > 0) {
            int cartNum = (int)session.getAttribute("cartNum");
            session.setAttribute("cartNum", cartNum - 1);
            return "success";
        } else {
            return "fail";
        }
    }

    @GetMapping("")
    public void index(Model model, HttpSession session) {
        User user = (User) session.getAttribute("user");
        List<Category> categories = categoryService.list();
//        System.out.println("user: " + user  );
        List<Cart> cartList = cartService.getCartByUserId(user.getId());
//        System.out.println("cartList: " + cartList);
        List<Cart> cartList1 = cartService.findGoodsByCart(cartList);
        model.addAttribute("cartList", cartList1);
        model.addAttribute("categories", categories);
    }

    @PostMapping("/update")
    @ResponseBody
    public String update(@RequestBody List<Cart> cartData ,HttpSession session) {
//        System.out.println("******************************************************");
//        System.out.println("carts: " + cartData);

        User user = (User) session.getAttribute("user");

        if(user == null) {
            return "fail";
        }
        boolean pd = true;
//        记录哪个商品不够
        StringBuilder goodsName = new StringBuilder();
        for(Cart cart : cartData) {
            Integer goodsId = cart.getGoodsId();
            Goods goods = goodsService.getById(goodsId);
            if(goods.getStock() < cart.getQuantity()) {
                pd = false;
                goodsName.append(goods.getName()).append(": ").append(goods.getStock()).append("\n");
            }
        }

        if(pd) {
            for(Cart cart : cartData) {
                int pd1 = cartService.updateCartQuantity(cart.getId(), cart.getQuantity());
                if(pd1 == 0) {
                    return "fail";
                }
            }
        }

        if(!pd) {
            return "商品库存不足\n" + goodsName;
        } else{
            return "success";
        }
    }

    @PostMapping("/queryGoodsNum")
    @ResponseBody
    public String queryGoodsNum(@RequestParam Integer goodsId, @RequestParam Integer goodsNum) {
        Goods goods = goodsService.getById(goodsId);
        System.out.println("queryGoodsNum goods: " + goods);
        if(goods == null || goods.getStock() < goodsNum) {
            return "fail";
        } else {
            return "success";
        }
    }
}
